import React, { useEffect, useState } from 'react';
import {
  Button,
  message,
  Popconfirm,
  Space,
  Table,
  Row,
  Col,
  Modal,
  Form,
  Input,
  DatePicker,
  Select,
  Upload,
} from 'antd';
import '../components.css';
import ReceiptService from '../../services/ReceiptService';
import {
  DeleteOutlined,
  UpCircleOutlined,
  PlusOutlined,
  SearchOutlined,
  SyncOutlined,
  UploadOutlined,
  DownloadOutlined,
} from '@ant-design/icons';
import moment from 'moment';
import AddReceipt from './AddReceipt';

const { RangePicker } = DatePicker;
const { Option } = Select;

export default function ReceiptManagement() {
  const [receipts, setReceipts] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectAll, setSelectAll] = useState(false);
  const [receiptDetail, setReceiptDetail] = useState(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [detailTime, setDetailTime] = useState(null);
  const [importLoading, setImportLoading] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [sortConfig, setSortConfig] = useState({
    key: 'id',
    direction: 'ascending',
  });

  // 显示票据详情弹窗
  const handleShowDetail = (record) => {
    setReceiptDetail(record);
    setDetailTime(moment());
    setDetailModalVisible(true);
  };

  // 表格分页、排序处理函数
  const handleTableChange = (pagination, filters, sorter) => {
    console.log('Pagination:', pagination);
    console.log('Filters:', filters);
    console.log('Sorter:', sorter);

    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...(filters && Object.keys(filters).reduce((acc, key) => {
        if (filters[key]) acc[key] = filters[key];
        return acc;
      }, {})),
      ...(sorter.field && {
        sortField: sorter.field,
        sortOrder: sorter.order === 'ascend' ? 'asc' : 'desc',
      }),
    };

    getAllReceipts(params);
  };

  // 排序切换（升序/降序）
  const handleSort = () => {
    setSortConfig((prevConfig) => ({
      key: 'id',
      direction: prevConfig.direction === 'ascending' ? 'descending' : 'ascending',
    }));
  };

  // 获取所有票据数据
  const getAllReceipts = (params = {}) => {
    setLoading(true);
    ReceiptService.getAllReceipts(params)
      .then((response) => {
        const formattedReceipts = response.data.map((receipt) => ({
          ...receipt,
          key: receipt.id,
          receiptPrice: receipt.receiptPrice || 0,
          receiptDate: receipt.receiptDate || new Date(),
        }));
        setReceipts(formattedReceipts);
        setLoading(false);
      })
      .catch((error) => {
        console.log(error);
        setLoading(false);
      });
  };

  // 导入CSV文件
  const handleImport = (info) => {
    setImportLoading(true);

    ReceiptService.importReceipts(info.file)
      .then((response) => {
        if (response.data === '导入成功') {
          message.success('导入成功！');
          getAllReceipts();
        } else {
          message.error('导入失败: ' + response.data);
        }
      })
      .catch((error) => {
        message.error('导入失败: ' + (error.response?.data || error.message));
      })
      .finally(() => {
        setImportLoading(false);
      });
  };

  // 导出CSV文件
  const handleExport = () => {
    const params = form.getFieldsValue();
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined && v !== '')
    );

    ReceiptService.exportReceipts(filteredParams)
      .then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `receipts_${moment().format('YYYYMMDDHHmmss')}.csv`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        message.success('导出成功！');
      })
      .catch((error) => {
        message.error('导出失败: ' + (error.response?.data || error.message));
      });
  };

  // 初始化加载数据
  useEffect(() => {
    getAllReceipts();
  }, []);

  // 多选操作
  const onSelectChange = (selectedKeys) => {
    setSelectedRowKeys(selectedKeys);
    setSelectAll(selectedKeys.length === receipts.length && receipts.length > 0);
  };

  const handleSelectAll = () => {
    if (selectAll) {
      setSelectedRowKeys([]);
    } else {
      setSelectedRowKeys(receipts.map((receipt) => receipt.id));
    }
    setSelectAll(!selectAll);
  };

  const handleInvertSelection = () => {
    const invertedSelection = receipts
      .map((receipt) => receipt.id)
      .filter((id) => !selectedRowKeys.includes(id));
    setSelectedRowKeys(invertedSelection);
    setSelectAll(false);
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请至少选择一项');
      return;
    }

    message.success('删除成功!');
    Promise.all(selectedRowKeys.map((id) => ReceiptService.deleteReceipt(id)))
      .then(() => {
        getAllReceipts();
        setSelectedRowKeys([]);
        setSelectAll(false);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 删除单条记录
  const deleteReceipt = (id) => {
    message.success('删除成功!');
    ReceiptService.deleteReceipt(id)
      .then(() => {
        getAllReceipts();
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 打开添加弹窗
  const showModal = () => {
    setIsModalVisible(true);
    setIsEditMode(false);
    setCurrentRecord(null);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const handleAddSuccess = () => {
    setIsModalVisible(false);
    getAllReceipts();
  };

  const handleAdd = () => {
    showModal();
  };

  // 搜索表单提交
  const onFinish = (values) => {
    const params = {
      receiptNumber: values.receiptNumber,
      receiptType: values.receiptType,
      receiptDate: values.receiptDate ? values.receiptDate.toDate() : undefined,
      receiptBelong: values.receiptBelong,
      receiptMiddle: values.receiptMiddle,
    };

    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined && v !== '')
    );

    getAllReceipts(filteredParams);
  };

  const onReset = () => {
    form.resetFields();
    getAllReceipts();
  };

  // 编辑记录
  const handleEditRecord = () => {
    if (!receiptDetail) return;

    setCurrentRecord({
      id: receiptDetail.key,
      relatedOrder: receiptDetail.relatedOrder,
      receiptDate: receiptDetail.receiptDate ? moment(receiptDetail.receiptDate) : null,
      receiptType: receiptDetail.receiptType,
      receiptPrice: receiptDetail.receiptPrice,
      receiptNumber: receiptDetail.receiptNumber,
      receiptContent: receiptDetail.receiptContent,
      receiptBelong: receiptDetail.receiptBelong,
      receiptMiddle: receiptDetail.receiptMiddle,
    });

    setIsEditMode(true);
    setIsModalVisible(true);
    setDetailModalVisible(false);
  };

  // 删除确认弹窗
  const handleDeleteRecord = () => {
    if (!receiptDetail) return;

    Modal.confirm({
      title: '确定删除这条记录吗?',
      content: '删除后将无法恢复',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        ReceiptService.deleteReceipt(receiptDetail.key)
          .then(() => {
            message.success('删除成功!');
            getAllReceipts();
            setDetailModalVisible(false);
          })
          .catch((error) => {
            console.log(error);
            message.error('删除失败!');
          });
      },
      onCancel: () => {
        message.info('已取消删除');
      },
    });
  };

  // 表格列配置
  const columns = [
    {
      title: '选择',
      key: 'selection',
      align: 'center',
      width: 60,
      render: (_, record) => (
        <input
          type="checkbox"
          checked={selectedRowKeys.includes(record.key)}
          onChange={() => {
            const newSelectedRowKeys = selectedRowKeys.includes(record.key)
              ? selectedRowKeys.filter((key) => key !== record.key)
              : [...selectedRowKeys, record.key];
            onSelectChange(newSelectedRowKeys);
          }}
        />
      ),
    },
    {
      title: '票据编号',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      sorter: true,
    },
    {
      title: '票据号码',
      dataIndex: 'receiptNumber',
      key: 'receiptNumber',
      align: 'center',
    },
    {
      title: '关联订单',
      dataIndex: 'relatedOrder',
      key: 'relatedOrder',
      align: 'center',
    },
    {
      title: '票据金额',
      dataIndex: 'receiptPrice',
      key: 'receiptPrice',
      align: 'center',
      render: (price) => `¥${price.toFixed(2)}`,
    },
    {
      title: '票据类型',
      dataIndex: 'receiptType',
      key: 'receiptType',
      align: 'center',
    },
    {
      title: '开票日期',
      dataIndex: 'receiptDate',
      key: 'receiptDate',
      align: 'center',
      render: (date) => (date ? moment(date).format('YYYY-MM-DD') : ''),
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<UpCircleOutlined />}
            onClick={() => handleShowDetail(record)}
          >
            详情
          </Button>
          <Popconfirm
            title="确定删除?"
            onConfirm={() => deleteReceipt(record.key)}
            onCancel={() => message.error('删除失败!')}
            okText="是"
            cancelText="否"
          >
            <Button type="danger" icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="emplst">
      <div className="title">票据管理</div>

      {/* 搜索表单 */}
      <Form
        form={form}
        layout="inline"
        onFinish={onFinish}
        style={{
          marginBottom: 20,
          background: '#fafafa',
          padding: 20,
          borderRadius: 4,
          display: 'flex',
          alignItems: 'center',
        }}
      >
        <div style={{ flex: 1, display: 'flex', gap: 16 }}>
          <Form.Item name="receiptNumber" style={{ flex: 1 }}>
            <Input placeholder="票据号码" />
          </Form.Item>

          <Form.Item name="receiptType" style={{ flex: 1 }}>
            <Select placeholder="票据类型" style={{ width: '100%' }}>
              <Option value="增值税专用发票">增值税专用发票</Option>
              <Option value="普通发票">普通发票</Option>
              <Option value="电子发票">电子发票</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>

          <Form.Item name="receiptDate" style={{ flex: 1 }}>
            <DatePicker style={{ width: '100%' }} placeholder="开票日期" format="YYYY-MM-DD" />
          </Form.Item>

          <Form.Item name="receiptBelong" style={{ flex: 1 }}>
            <Input placeholder="票据归属" />
          </Form.Item>

          <Form.Item name="receiptMiddle" style={{ flex: 1 }}>
            <Input placeholder="票据中间方" />
          </Form.Item>
        </div>

        <Form.Item style={{ marginLeft: 'auto' }}>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
            <Button onClick={onReset} icon={<SyncOutlined />}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <Row justify="space-between" style={{ marginBottom: 16 }}>
        <Col>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              添加票据
            </Button>

            <Upload
              accept=".csv"
              showUploadList={false}
              customRequest={handleImport}
              beforeUpload={(file) => {
                const isCsv = file.type === 'text/csv' || file.name.endsWith('.csv');
                if (!isCsv) {
                  message.error('只能上传CSV文件!');
                }
                return isCsv;
              }}
            >
              <Button
                type="primary"
                icon={<UploadOutlined />}
                loading={importLoading}
              >
                导入
              </Button>
            </Upload>

            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={handleExport}
            >
              导出
            </Button>
          </Space>
        </Col>
        <Col>
          <Space>
            <Button
              type="primary"
              icon={<UpCircleOutlined />}
              onClick={handleSort}
            >
              {sortConfig.direction === 'ascending' ? '升序' : '降序'}
            </Button>
          </Space>
        </Col>
      </Row>

      {/* 票据列表表格 */}
      <Table
        columns={columns}
        dataSource={receipts}
        bordered={true}
        loading={loading}
        pagination={{ pageSize: 10 }}
        onChange={handleTableChange}
      />

      {/* 批量操作按钮 */}
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Button onClick={handleSelectAll}>{selectAll ? '取消全选' : '全选'}</Button>
          <Button onClick={handleInvertSelection}>反选</Button>
          <Button
            type="primary"
            icon={<DeleteOutlined />}
            onClick={handleBatchDelete}
            danger
          >
            批量删除
          </Button>
        </Space>
      </div>

      {/* 票据详情弹窗 */}
      <Modal
        title="票据详情"
        visible={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="delete" danger onClick={handleDeleteRecord}>
            删除记录
          </Button>,
          <Button key="edit" type="default" onClick={handleEditRecord}>
            编辑记录
          </Button>,
          <Button key="close" type="primary" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={800}
      >
        {receiptDetail && (
          <div>
            <div style={{ marginBottom: 16, fontWeight: 'bold' }}>基本信息</div>

            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <tbody>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>
                    票据编号：
                  </td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{receiptDetail.id}</td>
                </tr>
                <tr>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>票据号码：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{receiptDetail.receiptNumber}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>
                    关联订单：
                  </td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{receiptDetail.relatedOrder}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>
                    票据金额：
                  </td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>
                    ¥{receiptDetail.receiptPrice?.toFixed(2)}
                  </td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>
                    票据类型：
                  </td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{receiptDetail.receiptType}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>
                    开票日期：
                  </td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>
                    {receiptDetail.receiptDate ? moment(receiptDetail.receiptDate).format('YYYY-MM-DD') : ''}
                  </td>
                </tr>
                <tr>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>票据内容：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{receiptDetail.receiptContent}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>
                    票据归属：
                  </td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{receiptDetail.receiptBelong}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>
                    票据中间方：
                  </td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{receiptDetail.receiptMiddle}</td>
                </tr>
              </tbody>
            </table>
          </div>
        )}
      </Modal>

      {/* 添加/编辑票据弹窗 */}
      <Modal
        title={isEditMode ? '编辑票据' : '添加票据'}
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={null}
        width={800}
        destroyOnClose
      >
        <AddReceipt
          onSuccess={handleAddSuccess}
          isEditMode={isEditMode}
          record={currentRecord}
        />
      </Modal>
    </div>
  );
}
